package com.example.newsdaily.slice;

import com.alibaba.fastjson.JSON;
import com.example.newsdaily.MyApplication;
import com.example.newsdaily.ResourceTable;
import com.example.newsdaily.entity.TUser;
import com.example.newsdaily.utl.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;

import ohos.data.preferences.Preferences;
import com.example.newsdaily.RegisterAbility;

public class LoginAbilitySlice extends AbilitySlice {
    Button btn_register;

    Checkbox remeberMe;
    TextField username,pwd;
    Button loginBtn;
    Preferences preferences=LocalDataUtil.preferences;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_Login);

        //得到页面中的组件
        username=(TextField)findComponentById(ResourceTable.Id_login_name);
        pwd=(TextField)findComponentById(ResourceTable.Id_login_pwd);
        loginBtn=(Button)findComponentById(ResourceTable.Id_login_lg);
        remeberMe=(Checkbox)findComponentById(ResourceTable.Id_reMe);
        btn_register=(Button)findComponentById(ResourceTable.Id_login_rgs);
        Boolean reMe= preferences.getBoolean(ContainUtil.USER_REMEMBER_KEY,false);
        if(reMe){
            //表示用户点了记住我
            //从轻量级数据库中读取用户名和密码并将其存储在当前页面的用户名密码中
            username.setText(preferences.getString(ContainUtil.USER_NAME_KEY,""));
            pwd.setText(preferences.getString(ContainUtil.USER_PASSWORD_KEY,""));
            //更改当前的记住我组件的选择状态
            remeberMe.setChecked(reMe);
            //代码登录
            login();
        }
        loginBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                login();
            }
        });
        btn_register.setClickedListener(component ->{
            Intent intent1=new Intent();
            Operation operation=new Intent.OperationBuilder()
                    .withBundleName(getBundleName())
                    .withAbilityName(RegisterAbility.class)
                    .build();
            intent1.setOperation(operation);
            startAbility(intent1);

        });

    }
    public void login(){
        //得到用户输入的内容
        String name=username.getText();
        String password=pwd.getText();
        ProgressDialogUtil progressDialogUtil=new ProgressDialogUtil(this);
        //判断是否为空Toast为发的工具，实现互动，最后一个为时长，倒数第二个为内容，倒数第三个为出现的界面位置
        if(name==null||name.trim().length()==0){
            ToastUtil.makeToast(this,"用户名不能为空!",ToastUtil.TOAST_LONG);
            return;
        }
        if(password==null||password.trim().length()==0){
            ToastUtil.makeToast(this,"密码不能为空!",ToastUtil.TOAST_LONG);
            return;
        }
        //添加进度条
        progressDialogUtil.showProgress(true);
        //实现登录功能
        //Thread有多个实例，多个参数
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        //访问登录接口
                        String result= HttpClientUtil.doGet(ContainUtil.HOST+ContainUtil.LOGIN+
                                "?name="+name+"&password="+password);
                        //添加UI线程
                        getUITaskDispatcher().asyncDispatch(
                                new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialogUtil.showProgress(false);
                                        //将Jason数据转换为User对象
                                        TUser tuser= JSON.parseObject(result,TUser.class);
                                        if(tuser==null){
                                            ToastUtil.makeToast(LoginAbilitySlice.this,"数据库当中没有这个人",ToastUtil.TOAST_LONG);
                                        }else{
                                            MyApplication.tuser = tuser;
                                            preferences.putLong(ContainUtil.USER_ID_KEY,tuser.getId());
                                            preferences.putBoolean(ContainUtil.USER_USED_KEY,true);
                                            if(remeberMe.isChecked()){
                                                preferences.putString(ContainUtil.USER_NAME_KEY,name);
                                                preferences.putString(ContainUtil.USER_PASSWORD_KEY,password);
                                                preferences.putBoolean(ContainUtil.USER_REMEMBER_KEY,true);
                                            }else{
                                                preferences.putString(ContainUtil.USER_NAME_KEY,name);
                                                preferences.putString(ContainUtil.USER_PASSWORD_KEY,"");
                                                preferences.putBoolean(ContainUtil.USER_REMEMBER_KEY,false);
                                            }
                                            ToastUtil.makeToast(LoginAbilitySlice.this,"登录成功",ToastUtil.TOAST_LONG);
                                            Intent intent = new Intent();

// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                                            Operation operation = new Intent.OperationBuilder()
                                                    .withDeviceId("")
                                                    .withBundleName("com.example.newsdaily")
                                                    .withAbilityName("com.example.newsdaily.MainAbility")
                                                    .build();

// 把operation设置到intent中
                                            intent.setOperation(operation);
                                            startAbility(intent);
                                        }

                                    }
                                }
                        );
                    }
                }
        ).start();
    }



    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
